package com.zay.a5_buttons.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.zay.a5_buttons.R;
import com.zay.a5_buttons.pojo.Book;
import java.util.List;

public class BookAdapter extends ArrayAdapter<Book> {
    private int resourceId;
    // 适配器的构造函数，把要适配的数据传入这里
    public BookAdapter(Context context, int textViewResourceId, List<Book> objects){
        super(context,textViewResourceId,objects);
        resourceId=textViewResourceId;
    }
    // convertView 参数用于将之前加载好的布局进行缓存
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        Book book=getItem(position); //获取当前项的Fruit实例

        // 加个判断，以免ListView每次滚动时都要重新加载布局，以提高运行效率
        View view;
        ViewHolder viewHolder;
        if (convertView==null){
            // 避免ListView每次滚动时都要重新加载布局，以提高运行效率
            view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            // 避免每次调用getView()时都要重新获取控件实例
            viewHolder=new ViewHolder();
            viewHolder.book_name=view.findViewById(R.id.book_name);
            viewHolder.book_publish=view.findViewById(R.id.book_publish);
            viewHolder.book_price=view.findViewById(R.id.book_price);
            // 将ViewHolder存储在View中（即将控件的实例存储在其中）
            view.setTag(viewHolder);
        } else{
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }
        // 获取控件实例，并调用set...方法使其显示出来
        viewHolder.book_name.setText(book.getBook_name());
        viewHolder.book_publish.setText(book.getBook_publish());
        viewHolder.book_price.setText(String.valueOf(book.getBook_pirce()));
        return view;
    }
    private final class ViewHolder{
        TextView book_name;
        TextView book_publish;
        TextView book_price;
    }
}
